/*
    Created by IntelliJ IDEA.
    @Auther: gaozhe
    @Date: 2020/5/15 上午 11:14
    
*/
package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import pojo.ResultInfo;
import pojo.User;
import service.UserService;
import service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/userRegister")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入userRegister");
        ResultInfo resultInfo = new ResultInfo();
        //获取验证码
        String user_checkCode = request.getParameter("check");
        String true_checkCode = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        System.out.println(true_checkCode);

        //验证
        if(true_checkCode.equalsIgnoreCase(user_checkCode)){//验证码正确
            //获取客户端的请求数据
            Map<String, String[]> map = request.getParameterMap();
            System.out.println("获取用户数据"+map);
            //将数据封装成对象
            User user  = new User();
            try {
                BeanUtils.populate(user,map);
            }catch (Exception e){
                e.printStackTrace();
            }
            //获取service层对象
            UserService userService  = new UserServiceImpl();
            boolean flag = userService.registerService(user);


            if(flag){
                //用户可以注册
                resultInfo.setFlag(true);
            }else{
                //用户无法注册
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("用户已存在！");

            }
            //将返回对象序列化为json
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(resultInfo);



            //设置浏览器接收数据格式为json
            response.setContentType("application/json;charset=utf-8");
            //将json数据发送至浏览器
            response.getWriter().write(json);
        }else{
            //验证码错误
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("验证码错误，请重试！！");
            //将返回对象序列化为json
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(resultInfo);
            //设置浏览器接收数据格式为json
            response.setContentType("application/json;charset=utf-8");
            //将json数据发送至浏览器
            response.getWriter().write(json);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }


}
